from flask import current_app, jsonify, render_template, g, abort, request

from info import constants, db
from info.models import News, Comment
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import news_blue

"""
评论接口
url:/news_comment
请求方式：POST
参数：news_id（新闻id） 、 comments（评论内容）、 parent_id（父评论--->可选）
"""


@news_blue.route('/news_comment', methods=['POST'])
@user_login_data
def news_comment():
	user = g.user

	params_dict = request.json
	news_id = params_dict.get('news_id')
	comment_str = params_dict.get('comment')
	parent_id = params_dict.get('parent_id')

	if not user:
		return jsonify(errno=RET.NODATA, errmsg='用户未登录')

	if not all([news_id, comment_str]):
		return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

	try:
		news = News.query.get(news_id)
	except Exception as e:
		current_app.logger.errror(e)
		return jsonify(errno=RET.DBERR, errmsg='数据库查找数据失败')

	if not news:
		return jsonify(errno=RET.NODATA, errmsg='该新闻不存在')

	comment = Comment()
	comment.news_id = news_id
	comment.user_id = user.id
	comment.content = comment_str
	if parent_id:
		comment.parent_id = parent_id

	try:
		db.session.add(comment)
		db.session.commit()
	except Exception as e:
		db.session.rollback()
		current_app.logger.errror(e)
		return jsonify(errno=RET.DBERR, errmsg='添加数据库失败')

	return jsonify(errno=RET.OK, errmsg='评论', data=comment.to_dict())


"""
新闻收藏接口
URL:/news_collect
请求方式：POST
参数：news_id(新闻id) 、 action(收藏or取消)
"""


@news_blue.route('/news_collect', methods=['POST'])
@user_login_data
def news_collect():
	user = g.user

	params_dict = request.json
	news_id = params_dict.get('news_id')
	action = params_dict.get('action')

	if not user:
		return jsonify(errno=RET.NODATA, errmsg='用户未登录')

	if not all([news_id, action]):
		return jsonify(errno=RET.PARAMERR, errmsg='参数不全')

	if action not in ['collect', 'cancel_collect']:
		return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

	try:
		news = News.query.get(news_id)
	except Exception as e:
		current_app.logger.errror(e)
		return jsonify(errno=RET.DBERR, errmsg='数据库查找数据失败')

	if not news:
		return jsonify(errno=RET.NODATA, errmsg='该新闻不存在')

	if action == 'cancel_collect':
		if news in user.collection_news:
			user.collection_news.remove(news)

	else:
		if news not in user.collection_news:
			user.collection_news.append(news)

	return jsonify(errno=RET.OK, errmsg='收藏成功')


"""
新闻详情页
URL:/news/
请求方式：GET
参数：新闻id
"""


@news_blue.route('/<int:news_id>')
@user_login_data
def get_news(news_id):
	# 一、登录信息
	user = g.user

	# 二、点击排行信息
	try:
		news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
	except Exception as e:
		current_app.logger.error(e)
		return jsonify(errno=RET.DBERR, errmsg='数据库查询新闻失败')

	news_dict_li = []
	for news in news_list:
		news_dict_li.append(news.to_basic_dict())

	# 三、新闻详情信息
	try:
		news = News.query.get(news_id)
	except Exception as e:
		current_app.logger.error(e)
		return jsonify(errno=RET.DBERR, errmsg='查询新闻失败')

	if not news:
		abort(404)
	# 四、点击量加一
	try:
		news.clicks += 1
		db.session.commit()
	except Exception as e:
		current_app.logger.errror(e)
		return jsonify(errno=RET.DBERR, errmsg='数据库查找数据失败')

	# 五、收藏&取消收藏
	is_collected = False

	if news in user.collection_news:
		is_collected = True

	# 六、评论信息
	try:
		comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
	except Exception as e:
		current_app.logger.errror(e)
		return jsonify(errno=RET.DBERR, errmsg='数据库查找数据失败')

	comment_dict_list = []
	for comment in comments:
		comment_dict_list.append(comment.to_dict())

	data = {
		'user': user.to_dict(),
		'news_dict_li': news_dict_li,
		'news': news.to_dict(),
		'is_collected': is_collected,
		'comments': comment_dict_list
	}

	return render_template('news/detail.html', data=data)
